package com.example.demo.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.model.User;

public class JWTUtil {

    private final static String ISSUER = "demon";
    private final static String USER_ID = "user_id";
    private final static String USER_NAME = "user_name";

    public static String createToken(User user, String secret) {
        String token = null;
        Date date = new Date();
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            token = JWT.create().withIssuer(ISSUER).withIssuedAt(date).withExpiresAt(DateUtil.addWeeks(date, 1))
                    .withClaim(USER_ID, user.getId()).withClaim(USER_NAME, user.getName())
                    .sign(algorithm);
        } catch (UnsupportedEncodingException exception) {
            token = null;
        } catch (JWTCreationException exception) {
            token = null;
        }
        return token;
    }

    public static User decodeToken(String token, String secret) {
        User user = new User();
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).acceptLeeway(5).build();
            DecodedJWT jwt = verifier.verify(token);

            user.setId(jwt.getClaim(USER_ID).asInt());
            user.setName(jwt.getClaim(USER_NAME).asString());
        } catch (UnsupportedEncodingException exception) {
            user = null;
        } catch (JWTVerificationException exception) {
            user = null;
        }
        return user;
    }

}
